package com.duofan.gmall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.duofan.gmall.common.utils.HttpUtils;
import com.duofan.gmall.member.entity.MemberLevelEntity;
import com.duofan.gmall.member.exception.PhoneExistException;
import com.duofan.gmall.member.exception.UsernameExistException;
import com.duofan.gmall.member.service.MemberLevelService;
import com.duofan.gmall.member.vo.SocialUser;
import com.duofan.gmall.member.vo.UserLoginVo;
import com.duofan.gmall.member.vo.UserRegVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duofan.gmall.common.utils.PageUtils;
import com.duofan.gmall.common.utils.Query;

import com.duofan.gmall.member.dao.MemberDao;
import com.duofan.gmall.member.entity.MemberEntity;
import com.duofan.gmall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void reg(UserRegVo vo) throws PhoneExistException, UsernameExistException {
        MemberEntity entity = new MemberEntity();
        // 设置默认等级
        MemberLevelEntity levelEntity = memberLevelService.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());
        // 检查用户名和手机号是否唯一,使用异常机制感知
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());
        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        // 昵称默认设置为用户名
        entity.setNickname(vo.getUserName());

        // 密码加密存储
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String passwordEncode = encoder.encode(vo.getPassword());
        entity.setPassword(passwordEncode);

        // 其他默认信息
        baseMapper.insert(entity);
    }

    @Override
    public MemberEntity login(UserLoginVo vo) {
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", vo.getAccount()).or().eq("mobile", vo.getAccount());
        MemberEntity entity = baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if(entity == null) {
            return null;
        } else {
            // 密码校验
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if(encoder.matches(vo.getPassword(), entity.getPassword())) {
                return entity;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser vo) throws Exception {
        // 登录和注册合并逻辑
        String uid = vo.getUid();
        String accessToken = vo.getAccessToken();
        Long expiresIn = vo.getExpiresIn();

        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", vo.getUid()));
        if(entity != null) {
            // 用户已注册
            MemberEntity updateEntity = new MemberEntity();
            updateEntity.setId(entity.getId());
            updateEntity.setAccessToken(accessToken);
            updateEntity.setExpiresIn(expiresIn);
            baseMapper.updateById(updateEntity);

            entity.setAccessToken(accessToken);
            entity.setExpiresIn(expiresIn);
            return entity;
        } else {
            MemberEntity regist = new MemberEntity();
            Map<String, String> header = new HashMap<>();
            Map<String, String> query = new HashMap<>();
            query.put("access_token", accessToken);
            query.put("uid", uid);
            try {
                // 查询当前社交用户的帐号信息
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get",
                        header, query);
                if(response.getStatusLine().getStatusCode() == 200) {
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    // 昵称
                    String name = jsonObject.getString("name");
                    // 性别
                    String gender = jsonObject.getString("gender");
                    /// 其他信息...
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                }
            } catch(Exception  e) {
                log.error(e.getMessage());
            }
            regist.setSocialUid(uid);
            regist.setAccessToken(accessToken);
            regist.setExpiresIn(expiresIn);
            baseMapper.insert(regist);
            return regist;
        }
    }

    /**
     * 校验手机号唯一性
     * @param phone
     * @throws PhoneExistException
     */
    private void checkPhoneUnique(String phone) throws PhoneExistException {
        int count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(count > 0) {
            throw new PhoneExistException();
        }
    }

    /**
     * 校验用户名唯一性
     * @param username
     * @throws UsernameExistException
     */
    private void checkUserNameUnique(String username) throws UsernameExistException {
        int count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if(count > 0) {
            throw new UsernameExistException();
        }
    }

}